(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('apf.finance.indvInvoiceListController', createController);
	createController.$inject = [ '$scope', '$filter', 'Constants', 'arithService', 'modalService', 'gridService', 'layoutConfig', 'validatorConfig', 'authService',
			'piDiscountService' ];
	function createController($scope, $filter, Constants, arithService, modalService, gridService, layoutConfig, validatorConfig, authService, piDiscountService) {
		var ctrl = this, piDiscountRequestInfo = $scope.$stateParams.params, errorMessage = {};
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		ctrl.piDiscountRequest = {};
		ctrl.amtChangedInv = {};
		ctrl.aa = true;

		ctrl.init = function() {
			ctrl.piDiscountRequest = piDiscountRequestInfo;
			ctrl.dateDisabled = piDiscountService.dateDisabled;
			ctrl.gridOptions = gridService.createGridOptions($scope, ctrl.layoutConfig.tableConfigs.table, paginationChanged, rowSelectionChanged, sortChanged);
			ctrl.gridOptions.data = 'vm.invoiceCriteria.list';
			ctrl.gridOptions.multiSelect = true;
			piDiscountRequestInfo.invoiceCriteria = ctrl.gridOptions.defaultSearchCriteria;
			piDiscountRequestInfo.invoiceCriteria.storageSearchCriteria = false;
			ctrl.invoiceCriteria = ctrl.gridOptions.defaultSearchCriteria;
			ctrl.invoiceCriteria.storageSearchCriteria = false;
			
			authService.create(ctrl.invoiceCriteria).then(function(response) {
				piDiscountService.getCurrencyOptions().then(function(currencyResponse) {
					ctrl.invoiceCcyOptions = currencyResponse.data;
					ctrl.invoiceCcyChanged =function(value, formCtrl, isInitialized){
						if(!isInitialized){
							ctrl.piDiscountRequest.totalFinanceAmt = 0;
							ctrl.invoiceCriteria.invoiceCcy = ctrl.piDiscountRequest.invoiceCcy;
							ctrl.search();
						}
					};
					ctrl.effectiveDateChanged =function(value, formCtrl, isInitialized){
						if(!isInitialized){
							ctrl.invoiceCriteria.effectiveDate = value.effectiveDate;
							ctrl.search();
						}
					};
					if (response.data && response.data.model) {
						var invoiceCriteria = response.data.model.invoiceCriteria;
						angular.forEach(invoiceCriteria.list, function(data) {
							if(data.communityCodeQ != null && data.communityCode != null){
								data.community = data.communityCodeQ + ":" + data.communityCode;
							}
							//change finance Amt
							if(ctrl.amtChangedInv.hasOwnProperty($filter('encode')(data.invoiceId))){
								data.financeAmt = ctrl.amtChangedInv[$filter('encode')(data.invoiceId)];
							}else{
								data.financeAmt = data.financeAvlAmt;
							}
							data.isFinanceAmtReadOnly = invoiceCriteria.isFinanceAmtReadOnly;
						});
						ctrl.piDiscountRequest = response.data.model;
						angular.merge(ctrl.invoiceCriteria, invoiceCriteria);
						ctrl.piDiscountRequest.availableAmount = invoiceCriteria.availableAmount;
						ctrl.piDiscountRequest.financeBy = response.data.model.financeBy;
						gridService.updateGridOptions(ctrl.invoiceCriteria, ctrl.gridOptions);
					}
				});
				
			});
		};
		
		ctrl.changeFinanceAmt = function(value, formCtrl, isInitialized){
			if(!isInitialized){
				var invoiceId = $filter('encode')(value.invoiceId);
				var financeAmt = $filter('encode')(value.financeAmt);
				ctrl.amtChangedInv[invoiceId] = financeAmt;
				ctrl.piDiscountRequest.totalFinanceAmt = 0;
				angular.forEach(ctrl.selectedRows, function(value, key) {
					ctrl.piDiscountRequest.totalFinanceAmt = parseFloat(arithService.add(ctrl.piDiscountRequest.totalFinanceAmt, value.financeAmt));
				});
			};
		};
		
		ctrl.search = function() {
			ctrl.invoiceCriteria.list = [];
			authService.create(ctrl.invoiceCriteria).then(
			function(response) {
				var invoiceCriteria = response.data.model.invoiceCriteria;
				angular.forEach(invoiceCriteria.list, function(data) {
					if(data.communityCodeQ != null && data.communityCode != null){
						data.community = data.communityCodeQ + ":" + data.communityCode;
					}
					//change finance Amt
					if(ctrl.amtChangedInv.hasOwnProperty($filter('encode')(data.invoiceId))){
						data.financeAmt = ctrl.amtChangedInv[$filter('encode')(data.invoiceId)];
					}else{
						data.financeAmt = data.financeAvlAmt;
					}
					data.isFinanceAmtReadOnly = invoiceCriteria.isFinanceAmtReadOnly;
				});
				angular.merge(ctrl.invoiceCriteria, invoiceCriteria);
				ctrl.piDiscountRequest.availableAmount = invoiceCriteria.availableAmount;
				ctrl.piDiscountRequest.financeBy = response.data.model.financeBy;
				if(ctrl.piDiscountRequest.effectiveDate > $scope.site.bizDate){
					ctrl.piDiscountRequest.isFutureDate = true;
				}else{
					ctrl.piDiscountRequest.isFutureDate = false;
				}
				gridService.updateGridOptions(ctrl.invoiceCriteria, ctrl.gridOptions);
			},angular.noop);
		};

		function paginationChanged(pageNum, pageSize) {
			ctrl.invoiceCriteria.pageNum = pageNum;
			ctrl.invoiceCriteria.pageSize = pageSize;
			ctrl.invoiceCriteria.list = [];
			ctrl.search();
		}

		ctrl.createContinue = function() {
			if (!ctrl.selectedRows || ctrl.selectedRows.length == 0) {
				modalService.openErrorDialogs({
					messages : [ 'title.dialogs.info.norecsel' ]
				});
				return;
			}
			ctrl.piDiscountRequest.discountInvoiceList = [];
			ctrl.piDiscountRequest.communityIds = [];
			ctrl.piDiscountRequest.amtChangedInv = ctrl.amtChangedInv;
			angular.forEach(ctrl.selectedRows, function(invoice, index) {
				ctrl.piDiscountRequest.discountInvoiceList.push(invoice);
				ctrl.piDiscountRequest.communityIds.push(invoice.communityId);
			});
			
			if(ctrl.piDiscountRequest.isFutureDate){
				return authService.createContinue(ctrl.piDiscountRequest).then(successful, failed);
			}else{
				return authService.createPreview(ctrl.piDiscountRequest).then(successful, failed);
			}
			
		};
		function failed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}
		
		function successful(response) {
			if (response.data && response.data.model) {
				var piDiscountRequest = response.data.model;
			}
			var params = {
					'selectedRows' : ctrl.selectedRows,
					'amtChangedInv' : ctrl.amtChangedInv,
					'piDiscountRequest' : piDiscountRequest,
					'financeBy' : ctrl.piDiscountRequest.financeBy
			};
			if(ctrl.piDiscountRequest.isFutureDate){
				$scope.go('apf.finance.create', params);
			}else{
				$scope.go('apf.finance.preview',params);
			}
		}
		
		function sortChanged(sortColumns) {
			// now just support sort by one column
			ctrl.invoiceCriteria.sortDirection = sortColumns[0] ? sortColumns[0].direction : '';
			ctrl.invoiceCriteria.sortBy = sortColumns[0] ? sortColumns[0].sortBy : '';
			ctrl.search();
		}
		
		function rowSelectionChanged(eventRow, selectedRows) {
			ctrl.piDiscountRequest.totalFinanceAmt = 0;
			angular.forEach(selectedRows, function(value, key) {
				ctrl.piDiscountRequest.totalFinanceAmt = parseFloat(arithService.add(ctrl.piDiscountRequest.totalFinanceAmt, value.financeAmt));
			});
			ctrl.selectedRows = selectedRows;
		}
	}
})(angular);